package com.example.demo.demos.web;

import com.example.demo.demos.entity.vo.RequestResult;
import com.example.demo.demos.entity.User;
import com.example.demo.demos.repository.UserRepository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Author: ft
 * @Date:2025/8/12
 * @Description: 相关单据：
 */
@RestController()
@RequestMapping("/user")
public class UserController {

    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @PostMapping("/login")
    public RequestResult login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {
        // JPA方式登录校验示例
        // 这里假设UserRepository已实现findByNameAndPassword方法
        User user = userRepository.findByNameAndPassword(username, password);
        if (user != null) {
            // 登录成功，生成token并存入session
            String token = UUID.randomUUID().toString();
            session.setAttribute("token", token);
            session.setAttribute("username", username);
            return new RequestResult(200, "登录成功", token);
        } else {
            return new RequestResult(401, "用户名或密码错误", null);
        }
    }

}